package com.ihome.android.util.log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

import com.ihome.android.util.TimeUtil;

public class LogThread extends Thread {
	private Process			logcatProc;

	private BufferedReader	mReader		= null;

	private boolean			mRunning	= true;

	private String			cmds		= null;

	private String			mPID;

	private OutputStream	out			= null;

	private File			file		= null;

	public LogThread(String mPID, File file) {
		this.mPID = mPID;
		this.file = file;
	}

	public void run() {

		try {

			cmds = "logcat *:v | grep \"(" + mPID + ")\"";

			out = new FileOutputStream(file);
			logcatProc = Runtime.getRuntime().exec(cmds);

			mReader = new BufferedReader(new InputStreamReader(logcatProc.getInputStream()), 1024);

			String line = null;

			while (mRunning && (line = mReader.readLine()) != null) {

				if (!mRunning) {
					break;
				}

				if (line.length() == 0) {
					continue;
				}

				if (out != null && line.contains(mPID)) {

					out.write((TimeUtil.getCurrentTime() + " " + line + "\n").getBytes());

				}

			}

		} catch (IOException e) {

			e.printStackTrace();

		} finally {

			if (logcatProc != null) {

				logcatProc.destroy();

				logcatProc = null;

			}

			if (mReader != null) {

				try {

					mReader.close();

					mReader = null;

				} catch (IOException e) {

					e.printStackTrace();

				}

			}

			if (out != null) {

				try {

					out.close();

				} catch (IOException e) {

					e.printStackTrace();

				}

				out = null;

			}

		}
	}
}